package com.cmbchina.service;

import com.cmbchina.entity.Currency;
import com.cmbchina.entity.ExchangeRate;
import com.cmbchina.entity.SinaExchangeRate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Objects;

/**
 * 汇率服务
 *  从新浪网站获取汇率
 */
@Service
public class SinaExchangeRateService implements ExchangeRateService{

    @Override
    public ExchangeRate getRate(Currency from, Currency to) {
        //1、从新浪网站获取新浪格式汇率
        SinaExchangeRate sinaRate = getSinaExchangeRate(from, to);
        //2、将新浪汇率格式转换为当前系统的汇率格式
        ExchangeRate rate = convertExhangeRate(sinaRate);
        return rate;
    }

    /**
     * 将新浪汇率格式转换当前系统汇率格式
     * @param sinaRate
     * @return
     */
    private ExchangeRate convertExhangeRate(SinaExchangeRate sinaRate){
        if(Objects.isNull(sinaRate)){
            throw new IllegalArgumentException("汇率不能为null");
        }
        Currency sourceCurrency = sinaRate.getSourceCurrency();
        Currency targetCurrency = sinaRate.getTargetCurrency();
        sinaRate.getRate();
        //格式转换
        BigDecimal rate = new BigDecimal(sinaRate.getRate());
        return new ExchangeRate(rate, sourceCurrency, targetCurrency);
    }

    /**
     * 从新浪网站获取汇率
     * @param from
     * @param to
     * @return
     */
    private SinaExchangeRate getSinaExchangeRate(Currency from, Currency to){
        //模拟从新浪网站获取汇率
        return new SinaExchangeRate("1.4", from, to);
    }
}
